package utils;

import java.sql.*;

public class DBUtil {
    // 数据库工具类
  private  static final   String url = "jdbc:mysql:///student_db?characterEncoding=utf8";
  private  static final   String username = "root";
  private  static final   String password = "123456";

  static {
      try {
          Class.forName("com.mysql.jdbc.Driver");
      } catch (ClassNotFoundException e) {
          e.printStackTrace();
      }
  }

  // 获取 连接对象
    public static Connection getConn(){
        Connection conn = null;
        try {
            conn = DriverManager.getConnection(url, username, password);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return conn;
    }

    // 翻译资源 的方法
    public static void close(Connection conn, PreparedStatement pst, ResultSet rs){
        try {
            if (rs!=null){
                rs.close();
            }
            if (pst!=null){
                pst.close();
            }
            if (conn!=null){
                conn.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }

    }

    // 通用的查询 select * from stu where id =? and name=?
    public static ResultSet query(String sql,Object... keys){
        Connection conn = getConn();
        ResultSet rs = null;
        try {
            PreparedStatement pst = conn.prepareStatement(sql);  // 预编译
            //  将 ？？？ 变成keys对应的值
            // [id=3,name=abc]
            // select * from stu where id =3 and name="abc"

            for (int i = 0; i < keys.length; i++) {
               pst.setObject((i+1),keys[i]);
            }

            // 执行sql
            rs = pst.executeQuery();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return rs;

    }


    // 通用的update
    public static int update(String sql,Object... keys){
        Connection conn = getConn();
        int num=0;
        try {
            PreparedStatement pst = conn.prepareStatement(sql);  // 预编译
            //  将 ？？？ 变成keys对应的值
            // [id=3,name=abc]
            // select * from stu where id =3 and name="abc"

            for (int i = 0; i < keys.length; i++) {
                pst.setObject((i+1),keys[i]);
            }

            // 执行sql
           num = pst.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return num;

    }
}
